// pages/messages/index/index.js
const commonUser = require('../../../common/commonUser.js');
const customRequst = require('../../../common/customRequst');
let app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    chat: {},
    session_list: [],
    userInfo: {},
    sysMsgNum: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    // 页面创建时执行

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    wx.hideTabBarRedDot({
      index: 2,
    });

    let that = this;
    let meInfo = commonUser.getUserInfo();
    if (meInfo == undefined || meInfo == null || meInfo == '') {
      wx.showModal({
        title: '登录提示',
        content: '您还未登录，请先登录！',
        success: function (res) {
          if (res.confirm) {
            let url = '/pages/messages/index/index'
            wx.navigateTo({
              url: '/pages/users/login/index?url=' + url,
            })
          }
        }
      });
      return;
    }
    that.setData({
      session_list: []
    });
    console.log(app.globalData.Chat.serviceConfig);
    app.globalData.Chat.windowsobj = this;
    if (!app.globalData.Chat.serviceConfig.isWebScoket) {
      let userIsLogin = commonUser.getUserToken();
      if (userIsLogin) {
        app.globalData.Chat.init();
      }
    }

    that.data.chat = app.globalData.Chat;

    //加载聊天列表
    let load_message = {
      c: 'Message',
      a: 'session_list',
      data: {
        agent_type: 'all'
      }
    };
    that.data.chat.sendMessage(load_message);

    //获取是否存在未读系统消息
    customRequst.postRequest('api/sysmsg/noreadnum', ).then(function (re) {
      if (re.code == 1) {
        if (re.data.num > 0) {
          that.setData({
            sysMsgNum: true
          })
        } else {
          that.setData({
            sysMsgNum: false
          })
        }
      } else {
      }
    })
  },

  //处理聊天返回的数据
  handleChatMag: function (msg) {
    let that = this;
    switch (msg.msgtype) {
      case 'config': //初始化连接完成
        break;
      case 'offline': //用户离线
        break;
      case 'online': //用户上线
        break;
      case 'message_list': //加载聊天列表
        if (msg.data.length >= 0) {
          for (let i in msg.data) {
            let item = msg.data[i];
            let avatar;
            let nickname;
            avatar = item.avatar;
            nickname = item.nickname;
            if (item.other && item.other != '') {
              let othrer = JSON.parse(item.other);
              if (othrer.peri_name && othrer.peri_name != '') {
                nickname = othrer.peri_name;
              }
              if (othrer.peri_image && othrer.peri_image != '') {
                avatar = othrer.peri_image;
                if (avatar.indexOf(that.data.chat.config.filepath) < 0) {
                  avatar = that.data.chat.config.filepath + avatar;
                }
              }
            }
            let pData = {
              "id": item.id,
              "session_user": item.session_user,
              "avatar": avatar,
              "nickname": nickname,
              "msg": item.last_message,
              "time": item.last_time,
              "msg_num": item.unread_msg_count,
              "bus_id": item.bus_id,
              'online': item.online,
            }
            that.data.session_list.unshift(pData);
          }
        };
        that.setData({
          session_list: that.data.session_list
        })
        break;
      case 'clear': //清除连接
        break;
      case 'new_message': //收到新消息
        //处理消息数字置顶
        let id = msg.data.id;
        let sessionList = that.data.session_list;
        let oldSession = '';
        for (let i in sessionList) {
          if (sessionList[i].id == id) {
            oldSession = sessionList[i];
            oldSession['msg_num'] = parseInt(oldSession['msg_num']) + 1;
            oldSession['msg'] =  msg.data.last_message;
            sessionList[i] = sessionList[0];
            sessionList[0] = oldSession;
            break;
          }
        }
        if (!oldSession) {
          let newNode = {
            "id": msg.data.id,
            "session_user": msg.data.session_user,
            "avatar": msg.data.avatar,
            "nickname": msg.data.nickname,
            "msg": msg.data.last_message,
            "time": msg.data.last_time,
            "msg_num": msg.data.unread_msg_count,
            "bus_id": 0,
            'online': msg.data.online,
          }
          sessionList.push(newNode);
        }
        that.setData({
          session_list: sessionList
        })
        break;
      case "push_sys_message":
        that.setData({
          sysMsgNum: true
        })
        break;
      default: //默认
        break;
    }
  },
  goChat(e) {
    let pers_id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/chat/chat?peris_id=' + pers_id
    })
  },
  handleNewMessage: function (msg) {},
  toList() {
    let that = this;
    that.setData({
      sysMsgNum: false
    });
    wx.navigateTo({
      url: '/pages/messages/list/list',
    })
  }
})